import { mapState } from 'vuex';
import { createAuditStructure } from '@/utils/aduitor';
import { createContract, createHistoryContract, editContract, formSubmit, processManagementDetail, queryFillFilePath, getLastTemplateInfo } from '@/api/legal';
import { platformList } from '@/api/select';
import { getIssueOurTitleList } from '@/api/issueInvoice';
import { valuationData, decrypt } from '@/utils';
import { isContained } from '@/utils/tools';
import fillFields from '../../module/fillFields';
import { downloadFile, deepClone, encryption } from '@/utils';
import processCreate from '@/mixins/processCreate';// 流程节点修改
// 使用改common.js 需要在使用地方定义legalParam
export default {
  mixins: [processCreate],
  data() {
    return {
      isSubmit: false,
      antiShakeTime: 0, // 防抖时间
      reapplyId: null, // 重新申请
      remodifyId: null, // 审批修改
      legalConstructionArg: {}, // 合同结构数据参数g
      processDetail: null,
      legalId: null,
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      previewPath: '', // 文件预览路径
      lastTemplate: { // 最后一次下载的合同模板信息
        fileName: '',
        filePath: '',
        id: '',
        sourceFilePath: ''
      },
      downloadLoading: false,
      subjectOptions: [],
      createNew: 0
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    proposer() {
      const { proposer, proposerId, post, proposerAvatar } = this.legalParam.createInfo;
      if (proposer) {
        return {
          userName: proposer.userName,
          avatar: proposerAvatar,
          id: proposerId,
          post: post
        };
      } else {
        const { id, userName, avatar, jobNumber } = this.userInfo;
        return {
          id,
          userName,
          avatar,
          number: jobNumber
        };
      }
    }
  },
  created() {
    this.createNew = Number(this.$route.query.createNew) || 0;
  },
  mounted() {
    this.getSubjectOptions();
  },
  watch: {
    legalDetail: {
      handler(newVal) {
        if (!newVal) return;
        /* const typeOfDetail = typeof newVal;
        if (typeOfDetail === 'object') { // 编辑流程
          this.initEdit(newVal);
          this.version = Number(newVal.version) || 0;// 当前详情版本，version存在mixins
        } else { // 新建流程
          this.initCreate(this.type);
        } */
        const legalId = decrypt(this.$route.params.id);
        if (!legalId) {
          this.initCreate(this.type);
        } else if (legalId) { // 编辑流程
          this.initEdit(newVal);
          this.version = Number(newVal.version) || 0;// 当前详情版本，version存在mixins
        }
      },
      immediate: true
    }
  },
  methods: {
    getSubjectOptions() {
      let temp = {};
      if (this.comLegalConstruction && this.comLegalConstruction.length) {
        temp = this.comLegalConstruction.find(item => {
          return item.title === '合同信息';
        }).children[1][1];
      }
      getIssueOurTitleList().then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.subjectOptions.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '所属公司'
            });
          });
        }
        temp.option = this.subjectOptions;
      });
    },
    submit(needCheckOrder = false) {
      if (this.isSubmit) return;
      const promiseValidate = [];
      promiseValidate.push(this.$refs['dynamicLegal'].$refs['dynamicLegalCreate']);
      !this.isPartTimeWorker && promiseValidate.push(this.$refs['contractRelevanceRef'].$refs['relatedContractTable']);
      Promise.all(promiseValidate.map(promise => promise.validate())).then((valid) => {
        if (valid) {
          // 判断关联合同是否存在相同的合同编号
          if (Array.isArray(this.legalParam.contractList) && this.legalParam.contractList.length > 1) {
            const sameNums = [];
            const numsMap = new Map();
            this.legalParam.contractList.forEach(item => {
              numsMap.has(item.contractNum) ? sameNums.push(item.contractNum) : numsMap.set(item.contractNum, true);
            });
            if (sameNums.length) {
              this.$message.error(`关联合同存在相同的合同编号：${sameNums.join('、')}`);
              return;
            }
            this.legalParam.contractList.forEach(it => {
              if (typeof it.proposerName === 'number') {
                it.proposer = it.proposerName;
              }
            });
          }
          if (this.legalParam.contractInfo.receivableAmount) this.legalParam.contractInfo.receivableAmount = Number(this.legalParam.contractInfo.receivableAmount);
          if (this.legalParam.contractInfo.payableAmount) this.legalParam.contractInfo.payableAmount = Number(this.legalParam.contractInfo.payableAmount);
          needCheckOrder ? this.checkOrder() : this.getProcessDetail();
        } else {
          this.$message.warning('请检查信息是否填写完整');
          return false;
        }
      }).catch(_ => {
        this.$message.error('请检查信息是否填写完整');
      });
    },
    checkOrder() {
      this.$refs.dynamicEditTableRef.validate().then(() => {
        this.getProcessDetail().then(_ => null);
      }).catch((_) => {
        this.$message.error('请检查关联订单填写是否完整');
      });
    },
    getProcess() {
      this.getProcessDetail(true).then(_ => null);
      this.isRefresh = true;
    },
    handlePost(params, message) { // 提交确认
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.setOppCompanyParams(params);
        this.postDataFun(params, message);
        return;
      }
      this.$confirm('提交申请后无法进行修改？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '再想想',
        center: true,
        type: 'warning',
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        this.setOppCompanyParams(params);
        this.postDataFun(params, message);
      });
    },
    getExplanation() { // 获取审批说明
      if (this.type === 10) { return; }// 过滤历史合同
      processManagementDetail({ id: this.type, type: this.mapContractType(this.type) }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.$emit('setExplanation', data.explanation, data.styConfig);
      }).catch(err => {
        console.log(err);
      });
    },
    queryLastTemplateInfo() {
      getLastTemplateInfo(this.type).then(res => {
        this.lastTemplate = res.data || {};
      });
    },
    setSaveDraftStatus() {
      // return (!this.reapplyId && !this.remodifyId && this.userInfo.id === this.legalParam.createInfo.createrId) || this.createNew;
      return (!this.reapplyId && !this.remodifyId) || this.createNew;
    },
    setSubmitStatus() {
      return true;
      // const createrId = (this.legalParam.createInfo && this.legalParam.createInfo.createrId);
      // const proposerId = (this.legalParam.createInfo && this.legalParam.createInfo.proposerId);
      // return (this.userInfo.id === createrId || this.userInfo.id === proposerId) || this.createNew;
    },
    setDetail(data, isCreateNew = 0) {
      const param = valuationData(this.legalParam, data);
      if (param.contractInfo.type !== 10) {
        const createInfo = data.createInfo;
        const contractInfo = data.contractInfo;
        const legalParamCreateInfo = param.createInfo;
        const legalParamContractInfo = param.contractInfo;
        this.defaultList['createInfo.proposer'] = [createInfo.proposer];
        legalParamCreateInfo.proposerId = createInfo.proposer ? createInfo.proposer.id : '';
        legalParamCreateInfo.departmentId = createInfo.department ? createInfo.department.id : '';
        if (createInfo.creatorDepartment) {
          legalParamCreateInfo.createrDepartmentId = createInfo.creatorDepartment.id;
          legalParamCreateInfo.createrDepartment = createInfo.creatorDepartment.value;
        }
        if (legalParamContractInfo.date && contractInfo.date && contractInfo.date.type === 1) {
          const startTime = contractInfo.date.startTime ? contractInfo.date.startTime : null;
          const endTime = contractInfo.date.endTime ? contractInfo.date.endTime : null;
          legalParamContractInfo.date.legalDate = startTime && endTime ? [startTime, endTime] : '';
        }
        if (createInfo.creator) {
          legalParamCreateInfo.createrId = createInfo.creator.id;
          legalParamCreateInfo.creater = createInfo.creator.userName;
        }
        legalParamCreateInfo.createrPost = createInfo.creatorPost || '--';
        if (data.orders && data.orders.length > 0) {
          data.orders.forEach(item => {
            if (!item.customizeState && !isCreateNew) {
              item.disable = true;
            }
            item.orderPrivateId = ++this.orderPrivateId;
          });
          this.orders = data.orders;
        }
        if (this.reapplyId) {
          legalParamCreateInfo.flowCode = '';
        }
        delete param.id;
      }
      this.legalParam = param;
      if (this.reapplyId) {
        this.initCreater();
        this.getExplanation();
        this.queryLastTemplateInfo();
      }
    },
    initEdit(val) {
      const legalId = decrypt(this.$route.params.id);
      const reapplyId = this.$route.query.reapply;
      const isCreateNew = Number(this.$route.query.createNew);
      if (reapplyId) {
        this.reapplyId = reapplyId;
      }
      this.remodifyId = decrypt(this.$route.query.remodify);
      this.remodifyId && (this.legalConstructionArg = { disabled: ['proposer', 'departmentId', 'post'] });
      if (legalId) { // 编辑走的逻辑
        this.legalId = legalId;
        this.setDetail(val, isCreateNew);
        const contractType = val.contractInfo.type;
        this.contractType = contractType;
        if (this.remodifyId) {
          this.oldAuditInfo = Object.assign({}, val.aduitInfo);
          this.processDetail = val.aduitInfo;
          this.legalParam.aduitInfo = val.aduitInfo;
        } else {
          this.getExplanation();
          this.queryLastTemplateInfo();
        }
      }
      this.platformList();
    },
    initCreate(type) {
      const contractType = type;
      if (contractType) { // 新建走的逻辑
        this.legalParam.contractInfo.type = Number(contractType);
        this.contractType = Number(contractType);
        this.getExplanation();// 审批说明
        this.queryLastTemplateInfo();
        this.initCreateData();
      }
      this.platformList();
    },
    initCreateData() { // 新建时初始化创建人信息
      if (!this.legalParam.createInfo) return;
      if (Object.keys(this.legalDetail).length > 0) {
        for (const i in this.legalDetail) {
          this.$set(this.legalParam, i, this.legalDetail[i]);
        }
      }
      const { deptName, departmentAry, id, userName, post, avatar, departmentName } = this.userInfo;
      if (deptName && deptName.length > 0) {
        // 3.2.1创建人部门展示子级部门名称，部门id依旧传一级部门id
        this.legalParam.createInfo.departmentId = deptName[0].id;
        this.legalParam.createInfo.createrDepartmentId = deptName[0].id;
        this.legalParam.createInfo.createrDepartment = departmentName[0];
      }
      this.$set(this.legalParam.createInfo, 'proposer', { id, userName, deptName, departmentAry, post, proposerAvatar: avatar });
      this.legalParam.createInfo.proposerAvatar = avatar;
      this.defaultList['createInfo.proposer'] = [{ id, userName, deptName, departmentAry, post, proposerAvatar: avatar }];
      this.legalParam.createInfo.proposerId = id;
      this.legalParam.createInfo.createrId = id;
      this.legalParam.createInfo.creater = userName;
      this.legalParam.createInfo.post = post || '--';
      this.legalParam.createInfo.createrPost = post || '--';
      this.legalParam.createInfo.departmentId = this.getFirstDepartment();
    },
    // 获取用户第一个部门的第一个子级部门
    getFirstDepartment() {
      const list = this.userInfo.departmentAry;
      if (Array.isArray(list) && list.length) {
        const deptIdArr = list[0].id;
        if (Array.isArray(deptIdArr) && deptIdArr.length) {
          return deptIdArr[deptIdArr.length - 1];
        } else {
          return null;
        }
      } else {
        return null;
      }
    },
    initCreater() {
      if (!this.legalParam.createInfo) return;
      const { deptName, id, userName, post, departmentName } = this.userInfo;
      if (deptName && deptName.length > 0) {
        this.legalParam.createInfo.createrDepartmentId = deptName[0].id;
        this.legalParam.createInfo.createrDepartment = departmentName[0];
      }
      this.legalParam.createInfo.createrId = id;
      this.legalParam.createInfo.creater = userName;
      this.legalParam.createInfo.createrPost = post || '--';
    },
    // 价格转换为number类型
    orderPriceSwitch(orders, type) {
      if (!orders) return;
      const tempOrders = JSON.parse(JSON.stringify(orders));
      tempOrders.forEach(i => {
        i['contractPrice'] = parseFloat(i['contractPrice']);
        i['publishPrice'] = parseFloat(i['publishPrice']);
      });
      return tempOrders;
    },
    // 获取流程详情
    getProcessDetail(isRefresh = false) {
      const data = deepClone(this.legalParam);
      this.setOppCompanyParams(data);
      data.type = this.mapContractType(this.type);
      return new Promise((resolve, reject) => {
        formSubmit(data).then(res => {
          if (res.code === 200) {
            const data = res.data;
            if (this.remodifyId && !isRefresh) {
              this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcess'].setShowRefresh(true);
            } else {
              this.processDetail = data;
              this.legalParam.aduitInfo.process = createAuditStructure(data.process, this.userInfo, this.proposer);
              this.legalParam.aduitInfo.id = data.id;
              this.legalParam.aduitInfo.senders = data.senderDiyUserList || [];
              resolve(data);
            }
            if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
              this.oldAuditInfo = Object.assign({}, data);
              this.oldAuditInfo.process.forEach(el => {
                this.oldAuditInfo.templateNodeId = el.id;
              });
              this.oldAuditInfo.activeTime = data.activationTime * 1000;
            }
            this.$refs['auditProcess'].openDrawer();
          } else {
            this.$message.error(res.message);
          }
        }).catch(err => {
          reject(err);
        });
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    // 合同类型与后端的一个映射
    mapContractType(type) {
      const obj = {
        1: 6,
        2: 1,
        3: 2,
        4: 5,
        5: 7,
        6: 8,
        7: 9,
        8: 10,
        9: 11
      };
      if (obj.hasOwnProperty(type)) {
        return obj[type];
      } else {
        return 1;
      }
    },
    toBack(type) {
      if (type === 10) {
        this.$router.push({
          name: 'ContractManagementHistory'
        });
        return;
      }
      this.$router.push({
        name: 'ContractManagement'
      });
      /* if (this.remodifyId) {
        this.$router.push({
          name: 'contractDetail',
          params: {
            id: this.legalId
          },
          query: {
            processId: this.remodifyId
          }
        });
      } */
    },
    toBackStep() {
      this.$emit('toBackStep', this.legalParam);
    },
    saveDraft() {
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 600) {
        return;
      }
      this.antiShakeTime = timestamp;
      if (this.isSubmit) return;
      const params = JSON.parse(JSON.stringify(this.legalParam));
      // 先点击发起审批未提交再点击保存草稿，不需处理签约对方参数
      typeof params.contractInfo.oppCompany !== 'string' && this.setOppCompanyParams(params);
      params.submitType = 1;
      if (this.orders && this.orders.length > 0) {
        params.orders = this.orderPriceSwitch(this.orders, 2);
      }
      delete params.createInfo.proposer;
      if (this.$route.query.signUpId) {
        params.signUpId = Number(this.$route.query.signUpId);
      }
      if (params.contractList && params.contractList.length) {
        params.contractList.forEach(it => {
          if (typeof it.proposerName === 'number') {
            it.proposer = it.proposerName;
          }
        });
      }
      this.postDataFun(params, '草稿保存成功');
    },
    postDataFun(params, message) {
      this.isSubmit = true;
      params.isEditAudit = false;
      params.type = this.mapContractType(this.type);// 2.9.7增加流程type
      this.setOppCompanyParams(params);
      if (this.remodifyId && this.isRefresh) {
        params.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      if (params.contractInfo && params.contractInfo.deadline === '') {
        params.contractInfo.deadline = [];
      }
      if (params.contractInfo && params.contractInfo.contractDate === '') {
        params.contractInfo.contractDate = [];
      }
      if (params.authorBillInfo && params.authorBillInfo.deadline && params.authorBillInfo.deadline.date === '') {
        params.authorBillInfo.deadline.date = [];
      }
      const createApi = params.contractInfo.type === 10 ? createHistoryContract : createContract;
      if (!this.legalId || this.reapplyId || this.createNew) {
        createApi(params).then(res => {
          this.isSubmit = false;
          if (res.code === 200) {
            const freshCreateSignUp = localStorage.getItem('freshCreateSignUp') || 0;
            localStorage.setItem('freshCreateSignUp', Number(freshCreateSignUp) + 1);
            this.$message({
              type: 'success',
              message
            });
            // KOL
            if (params.contractInfo.type === 5 && this.$route.query.signUpId && this.isInFeiShu) {
              this.toSignUpDetail();
              return;
            }
            if (params.contractInfo.type !== 10 && res.data.id && res.data.processId) {
              this.$router.push({
                name: 'contractDetail',
                params: {
                  id: res.data.id
                },
                query: {
                  processId: res.data.processId
                }
              });
            } else {
              this.toBack(params.contractInfo.type);
            }
          }
        }).catch(err => {
          this.isSubmit = false;
          if (err.code === 502) {
            this.$refs['auditProcess'].setShowRefresh(true);
          }
        });
      } else {
        editContract(this.legalId, params).then(res => {
          this.isSubmit = false;
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message
            });
            if (params.contractInfo.type !== 10 && res.data.id && res.data.processId) {
              this.$router.push({
                name: 'contractDetail',
                params: {
                  id: res.data.id
                },
                query: {
                  processId: res.data.processId
                }
              });
            } else {
              this.toBack(params.contractInfo.type);
            }
          }
        }).catch(err => {
          this.isSubmit = false;
          if (err.code === 502) {
            this.$refs['auditProcess'].setShowRefresh(true);
          }
          if (err.code === 505) { // 节点修改跳转详情
            this.nodeModifyJumpDetail({ routeName: 'contractDetail', params: { id: encryption(this.legalId) }, query: { processId: encryption(this.remodifyId) }});
          }
        });
      }
    },
    // 获取下单平台的列表
    async platformList() {
      try {
        const result = await platformList();
        if (this.legalOrderSetting) {
          this.legalOrderSetting.forEach(i => {
            if (i.label === '下单平台') {
              this.$set(i, 'options', result.data);
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 如果是选择 不勾选 加签人的话 需要对数据中的加签项 进行清空
    removeSigner(aduitInfo) {
      const data = JSON.parse(JSON.stringify(aduitInfo));
      data.process.forEach(process => {
        if (process.isCountersign) {
          process.examineRoles.forEach(examineRole => {
            examineRole.aduitors = [];
          });
        }
      });
      return data;
    },
    // 打开合同模板弹窗
    showTemplateDrawer() {
      this.$refs['contractTemplateRef'].dialogVisible = true;
    },
    // 打开合同预览弹窗
    showPreviewDrawer() {
      this.downloadTemplate(null, true, false);
      this.$refs['ContractPreviewRef'].dialogVisible = true;
    },
    // 下载/获取填充文件地址
    downloadPreviewFile(data, isDownload = false) {
      const params = Object.create(null);
      params.id = data.id;
      params.contractType = this.contractType;
      params.name = data.fileName;
      this.downloadTemplate(params, true, isDownload);
    },
    // 合同模板下载
    downloadTemplate(rowData = null, isFill = false, isDownload = true) {
      if (isFill) { // 下载填充模板
        const params = Object.create(null);
        if (rowData) { // 列表下载
          Object.assign(params, rowData);
        } else { // 发起审批下载
          params.contractType = this.legalParam.contractInfo.type;
          params.id = this.lastTemplate.id;
        }
        params.fields = Object.create(null);
        const fields = fillFields[params.contractType];
        Object.keys(fields).forEach(key => {
          params.fields[key] = _.get(this.legalParam, fields[key]);
        });
        params.isDownload = +(!!isDownload);
        isDownload && (this.downloadLoading = true);
        this.setOppCompanyParams(params, 'fields');
        queryFillFilePath(params).then(res => {
          const { path } = res.data;
          if (isDownload) {
            const name = rowData ? params.name : this.lastTemplate.fileName;
            downloadFile(path, name);
          } else { // 仅获取预览地址
            this.previewPath = res.data && res.data.path;
          }
          this.downloadLoading = false;
        }).catch(() => {
          this.previewPath = '';
          this.downloadLoading = false;
        });
      } else { // 下载空模板
        downloadFile(this.lastTemplate.filePath, this.lastTemplate.fileName);
      }
    },
    // 发起审批/保存草稿时修改一下签约对方的参数
    setOppCompanyParams(params, key) {
      key = key || 'contractInfo';
      if (params[key].oppCompany && typeof params[key].oppCompany === 'object') {
        const temp = JSON.parse(JSON.stringify(params[key].oppCompany));
        params[key].oppCompanyId = temp.id;
        params[key].oppCompany = temp.name;
        params[key].oppCompanyType = temp.type;
      }
    }
  }
};
